import hx.geom.Point;
import openfl.geom.Vector3D;
import openfl.geom.Matrix3D;
import openfl.Vector;
import hx.display.Box;
import openfl.geom.PerspectiveProjection;
import hx.display.Graphics;
import openfl.geom.Utils3D;
import hx.display.Quad;
import hx.display.FPS;
import hx.display.Image;
import hx.assets.Assets;
import hx.display.Stage;

class GameStage extends Stage {
	override function onStageInit() {
		super.onStageInit();
		// 代码开始的地方...

		var quad = new Quad(100, 100, 0xffff00);
		this.addChild(quad);
		quad.x = 300;
		quad.y = 300;

		var box3d = new Box3D();
		this.addChild(box3d);
		// box3d.x = stage.stageWidth / 2;
		// box3d.y = 300;
		box3d.y = 350;
		box3d.x = 350;
	}
}

class Box3D extends Box {
	public var array:Array<Quad> = [];

	public function new() {
		super();
		for (i in 0...8) {
			var quad = new Quad(5, 5, 0xff0000);
			array.push(quad);
			this.addChild(quad);
		}
		array[0].x = -50;
		array[0].y = -50;
		array[1].x = 50;
		array[1].y = -50;
		array[2].x = 50;
		array[2].y = 50;
		array[3].x = -50;
		array[3].y = 50;

		array[4].x = -50;
		array[4].y = -50;
		array[5].x = 50;
		array[5].y = -50;
		array[6].x = 50;
		array[6].y = 50;
		array[7].x = -50;
		array[7].y = 50;

		var v = new Vector<Float>();
		for (i => quad in array) {
			v.push(quad.x);
			v.push(quad.y);
			if (i >= 4) {
				v.push(50);
			} else {
				v.push(-50);
			}
		}

		var tx = 0;
		var r = 0;
		var project = new PerspectiveProjection();
		this.addEventListener(hx.events.Event.UPDATE, function(e) {
			// trace("frame");
			project.fieldOfView = 45;
			// project.focalLength = stage.stageHeight;
			// project.projectionCenter.x = stage.stageWidth / 2;
			// project.projectionCenter.y = stage.stageHeight / 2;
			var proj = project.toMatrix3D();

			// r++;
			r = r % 360;

			// tx--;

			var mat = new Matrix3D();
			mat.identity();
			mat.appendRotation(r, Vector3D.X_AXIS);
			var s = stage.stageWidth / stage.stageHeight;
			mat.appendTranslation(0, 0, 800);
			mat.append(proj);

			var uvts = new Vector<Float>();
			for (quad in array) {
				uvts.push(0);
				uvts.push(0);
				uvts.push(0);
			}

			var p = new Vector<Float>();
			Utils3D.projectVectors(mat, v, p, uvts);
			// trace(uvts);
			var counts = Std.int(p.length / 2);
			for (i in 0...counts) {
				array[i].x = p[i * 2];
				array[i].y = p[i * 2 + 1];
				// array[i].scaleX = uvts[i * 3];
				// array[i].scaleY = uvts[i * 3];
			}
		});
	}
}
